package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessFarmSystem;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.MyOrderListVO;
import com.digitalchina.lxnsy.entity.PayVO;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.wxapi.WXPayEntryActivity;
import com.facebook.drawee.view.SimpleDraweeView;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/8/8 10:28
 * 修改备注：
 * ================================================
 */
public class OrderDetailsActivity extends BaseActivity {

    @Bind(R.id.order_details_order_number)
    TextView orderDetailsOrderNumber; // 订单号
    @Bind(R.id.order_details_order_date)
    TextView orderDetailsOrderDate; // 日期
    @Bind(R.id.order_details_logistics_name)
    TextView orderDetailsLogisticsName; // 物流公司
    @Bind(R.id.order_details_logistics_number)
    TextView orderDetailsLogisticsNumber; // 快递号
    @Bind(R.id.order_details_person_name)
    TextView orderDetailsPersonName; // 收货人
    @Bind(R.id.order_details_person_mobile)
    TextView orderDetailsPersonMobile; // 联系电话
    @Bind(R.id.order_details_show_address)
    TextView orderDetailsShowAddress; // 地址
    @Bind(R.id.activity_order_details_ll_layout)
    LinearLayout activityOrderDetailsLlLayout; // 商品容器layout
    @Bind(R.id.order_details_goods_total_price)
    TextView orderDetailsGoodsTotalPrice; // 实付款
    @Bind(R.id.order_details_goods_total_freight_price)
    TextView orderDetailsGoodsTotalFreightPrice; // 邮费 格式 "（含运费10元）"
    @Bind(R.id.order_details_total_goods_num)
    TextView orderDetailsTotalGoodsNum; // 商品数量  格式 "共2件商品"
    @Bind(R.id.order_details_seller_name)
    TextView orderDetailsSellerName; // 商家名称
    @Bind(R.id.order_details_seller_logo)
    SimpleDraweeView orderDetailsSellerLogo; // 商家logo
    @Bind(R.id.order_details_seller_phone)
    TextView orderDetailsSellerPhone; // 商家电话


    @Bind(R.id.order_details_btn_left)
    Button orderDetailsBtnLeft; // 左按钮
    @Bind(R.id.order_details_btn_right)
    Button orderDetailsBtnRight; // 右按钮


    private MyOrderListVO myOrderListVO;


    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_order_details);
        setTitle("订单详情");
    }

    @Override
    public void initMember() {
        myOrderListVO = (MyOrderListVO) getIntent().getSerializableExtra("MyOrderListVO");

        setView();
    }

    /**
     * 设置视图
     */
    private void setView() {
        // 订单号
        orderDetailsOrderNumber.setText("订单号：" + myOrderListVO.getOrderNo());
        // 日期
        orderDetailsOrderDate.setText(myOrderListVO.getCreateTime());
        if (myOrderListVO.getLogistics() != null) {
            // 物流公司
            orderDetailsLogisticsName.setText(myOrderListVO.getLogistics().getDeliveryCorp());
            // 快递号
            orderDetailsLogisticsNumber.setText(myOrderListVO.getLogistics().getTrackingNo());
        } else {
            // 物流公司
            orderDetailsLogisticsName.setText("暂无");
            // 快递号
            orderDetailsLogisticsNumber.setText("暂无");
        }
        // 收货人
        orderDetailsPersonName.setText(myOrderListVO.getConsignee());
        // 联系电话
        orderDetailsPersonMobile.setText(myOrderListVO.getShippingPhone());
        // 地址
        orderDetailsShowAddress.setText(myOrderListVO.getShippingAddress());
        // 商品总价
        orderDetailsGoodsTotalPrice.setText(myOrderListVO.getTotalPriceReal() + "");
        // 商品总价
        orderDetailsGoodsTotalFreightPrice.setText("（含运费" + myOrderListVO.getFreightPriceReal() + "元）");
        // 商品数量
        int num = 0;
        if (myOrderListVO.getOrderItems() != null) {
            num = myOrderListVO.getOrderItems().size();
            activityOrderDetailsLlLayout.removeAllViews();
            for (int i = 0; i < num; i++) {
                View goodsLayout = LayoutInflater.from(this).inflate(R.layout.item_goods, null);

                SimpleDraweeView goodsPic = (SimpleDraweeView) goodsLayout.findViewById(R.id.item_goods_iv_picture);
                TextView goodsName = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_name);
                TextView goodsPrice = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_price);
                TextView goodsNum = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_num);
                TextView attrName = (TextView) goodsLayout.findViewById(R.id.item_goods_tv_attrName);

                attrName.setText(myOrderListVO.getOrderItems().get(i).getAttrName() != null ? myOrderListVO.getOrderItems().get(i).getAttrName() : "无属性");
                goodsName.setText(myOrderListVO.getOrderItems().get(i).getProductName());

                FrescoUtil.showImageSmall(myOrderListVO.getOrderItems().get(i).getProductImg(), goodsPic);
                goodsPrice.setText(String.format("￥ %s", myOrderListVO.getOrderItems().get(i).getPrice()));
                goodsNum.setText(String.format("x %s", myOrderListVO.getOrderItems().get(i).getQuantity()));

                activityOrderDetailsLlLayout.addView(goodsLayout);
            }
        }

        orderDetailsTotalGoodsNum.setText("共" + num + "件商品");
        // 商家名称
        orderDetailsSellerName.setText(myOrderListVO.getSellerName());
        // 商家logo
        FrescoUtil.showImageSmall(myOrderListVO.getSellerLogo(), orderDetailsSellerLogo);
        // 商家电话
        orderDetailsSellerPhone.setText(myOrderListVO.getSellerPhone());


        switch (myOrderListVO.getEqualStatus()) {
            case Constant.ORDER_STATUS_POST_WAIT_DELIVERY://待发货
                setButtonText("", "取消订单");
                orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cancelOrder();
                    }
                });
                break;
            case Constant.ORDER_STATUS_POST_WAIT_RECEIVING://待收货
                setButtonText("查看物流", "确认收货");

                orderDetailsBtnLeft.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        GotoUtil.gotoActivity(OrderDetailsActivity.this, LogisticsQueryActivity.class, "orderNo", myOrderListVO.getOrderNo());
                    }
                });

                orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new MaterialDialog.Builder(OrderDetailsActivity.this)
                                .title("提示")
                                .content("是否确认收货？")
                                .positiveText("确定")
                                .negativeText("取消")
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        BusinessFarmSystem.affirmReceipt(OrderDetailsActivity.this, myOrderListVO.getOrderNo(), mHandler);
                                    }
                                })
                                .show();
                    }
                });
                break;
            case Constant.ORDER_STATUS_POST_WAIT_EVALUATE://待评价
                setButtonText("删除订单", "评价");
                orderDetailsBtnLeft.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteOrder();
                    }
                });
                orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        GotoUtil.gotoForResultActivity(OrderDetailsActivity.this, EvaluateOrderActivity.class, 99, "myOrderListVO", myOrderListVO);
                    }
                });
                break;
            case Constant.ORDER_STATUS_POST_CLOSE://已关闭
                setButtonText("", "删除订单");

                orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteOrder();
                    }
                });
                break;
            case Constant.ORDER_STATUS_POST_CANCEL://已取消
                setButtonText("", "删除订单");
                orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteOrder();
                    }
                });

                break;
            case Constant.ORDER_STATUS_POST_WAIT_PAYMENT://待支付
                setButtonText("取消订单", "支付");
                orderDetailsBtnLeft.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cancelOrder();
                    }
                });
                orderDetailsBtnRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PayVO payVO = new PayVO();
                        payVO.setPrice(myOrderListVO.getTotalPriceReal());
                        payVO.setOrderNO(myOrderListVO.getOrderNo());
                        payVO.setType(1);
                        GotoUtil.gotoActivity(OrderDetailsActivity.this, WXPayEntryActivity.class, "payVO", payVO);
                    }
                });
                break;

        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 99 && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    /**
     * 删除订单
     */
    private void deleteOrder() {
        new MaterialDialog.Builder(OrderDetailsActivity.this)
                .title("提示")
                .content("是否确认删除该订单？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        BusinessFarmSystem.deleteOrder(OrderDetailsActivity.this, myOrderListVO.getOrderNo(), mHandler);
                    }
                })
                .show();
    }

    /**
     * 取消订单
     */
    private void cancelOrder() {
        new MaterialDialog.Builder(OrderDetailsActivity.this)
                .title("提示")
                .content("您确定要取消订单吗？")
                .items(R.array.cancelReason)
                .itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {
                    @Override
                    public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                        if (text == null || text == "") {
                            showToast("请选择一个理由！");
                            return true;
                        }
                        BusinessFarmSystem.cancelOrder(OrderDetailsActivity.this, myOrderListVO.getOrderNo(), text.toString(), mHandler);
                        return true;
                    }
                })
                .positiveText("确定")
                .negativeText("取消")
                .show();
    }

    /**
     * 设置左右button 如果为空则隐藏button
     *
     * @param leftButtonText
     * @param rightButtonText
     */
    private void setButtonText(String leftButtonText, String rightButtonText) {
        // 左边按钮
        if (StringUtil.isStrEmpty(leftButtonText))
            orderDetailsBtnLeft.setVisibility(View.GONE);
        else
            orderDetailsBtnLeft.setText(leftButtonText);
        // 右边按钮
        if (StringUtil.isStrEmpty(rightButtonText))
            orderDetailsBtnRight.setVisibility(View.GONE);
        else
            orderDetailsBtnRight.setText(rightButtonText);
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_CANCEL_ORDER_AGSRV_SUCCESS:
                        showToast("订单已取消");
                        setResult(RESULT_OK);
                        finish();
                        break;
                    case MSG.MSG_CANCEL_ORDER_AGSRV_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_DELETE_ORDER_AGSRV_SUCCESS:
                        showToast("订单已删除");
                        setResult(RESULT_OK);
                        finish();
                        break;
                    case MSG.MSG_DELETE_ORDER_AGSRV_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_AFFIRM_RECEIPT_SUCCESS:
                        showToast("已确认收货");
                        setResult(RESULT_OK);
                        finish();
                        break;
                    case MSG.MSG_AFFIRM_RECEIPT_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

}
